package io.renren.modules.lables.dao;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

@Service
@Slf4j
public class LableDao {
   static final String DB_URL = "jdbc:mysql://doris:9030/labels";
   static final String USER = "root";
   static final String PASS = "000000";

   public static void createTable(String tableName) throws Exception {
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
          Statement stmt = conn.createStatement();
      ) {
          String sqlStatement = "CREATE TABLE IF NOT EXISTS " + tableName + " (\n" +
                  "  tagname VARCHAR(20) COMMENT 'tagname',\n" +
                  "  tagvalue VARCHAR(20) COMMENT 'tagvalue',\n" +
                  "  distinct_id VARCHAR(20) COMMENT 'distinct_id',\n" +
                  "  userid BIGINT COMMENT 'userid',\n" +
                  "  subject VARCHAR(20) COMMENT 'subject',\n" +
                  "  inserttime DATETIME COMMENT 'inserttime'\n" +
                  ") ENGINE=OLAP\n" +
                  " AGGREGATE KEY(`tagname`, `tagvalue`, `distinct_id`, `userid`,`subject`,`inserttime`)\n" +
                  "  PARTITION BY RANGE(`inserttime`) (\n" +
                  "    PARTITION p2020 VALUES LESS THAN (\"2021-01-01 12:00:00\"),\n" +
                  "    PARTITION p2021 VALUES LESS THAN (\"2022-01-01 12:00:00\"),\n" +
                  "    PARTITION p2022 VALUES LESS THAN (\"2023-01-01 12:00:00\"),\n" +
                  "    PARTITION p2023 VALUES LESS THAN MAXVALUE\n" +
                  "  )\n" +
                  "  DISTRIBUTED BY HASH(`subject`) BUCKETS 2\n" +
                  "PROPERTIES\n" +
                  "(\n" +
                  " \"replication_num\" = \"1\"\n" +
                  ");";

          stmt.executeUpdate(sqlStatement);
         log.info("Created table in given database...");
      } catch (SQLException e) {
          log.error(e.getMessage());
      }
   }

}